/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.fspike.gui.dialog;

import com.compomics.fspike.contentprovider.webprovider.UniprotContentProvider;
import java.awt.Frame;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

/**
 *
 * @author Kenneth
 */
public class DialogUniprotContaminant extends javax.swing.JDialog {

    private String spikeName;
    private Map<String, String> spikeSequenceMap;
    private JList jList;
    private Frame parentFrame;

    /**
     * Creates new form DialogKnownContaminants
     */
    public DialogUniprotContaminant(JList jList, Map<String, String> contaminationMap, java.awt.Frame parentFrame, boolean modal) {
        super(parentFrame, modal);
        this.spikeSequenceMap = contaminationMap;
        this.jList = jList;
        this.parentFrame = parentFrame;
        initComponents();
        this.setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        searchOptionComboBox = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        cancelButton = new javax.swing.JButton();
        spikeNameTextField = new javax.swing.JTextField();
        searchButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Add a uniprot entry as contaminant");

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        searchOptionComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Protein Name", "Accession", " " }));
        searchOptionComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchOptionComboBoxActionPerformed(evt);
            }
        });

        jLabel1.setText("Uniprot Spike");

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        spikeNameTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                spikeNameTextFieldActionPerformed(evt);
            }
        });

        searchButton.setText("Search");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(searchOptionComboBox, 0, 93, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(searchButton))
                    .addComponent(spikeNameTextField))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(spikeNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchOptionComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed

        final JDialog dialog = getWaitingDialog("Contacting UniProt...");
        SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

            @Override
            protected Void doInBackground() {
                if (searchOptionComboBox.getSelectedItem().toString().equalsIgnoreCase("Accession")) {
                    getFromUniprotAccession();
                } else if (searchOptionComboBox.getSelectedItem().toString().equalsIgnoreCase("Protein Name")) {
                    getFromUniprotTerm();
                }
                return null;
            }

            @Override
            protected void done() {
                dialog.dispose();
            }
        };
        worker.execute();
        dialog.setVisible(true); // will block but with a responsive GUI


    }//GEN-LAST:event_searchButtonActionPerformed

    private JDialog getWaitingDialog(String message) {
        final JDialog dialog = new JDialog(this, true); // modal  
        dialog.setUndecorated(true);
        dialog.setLocationRelativeTo(null);
        JProgressBar bar = new JProgressBar();
        bar.setIndeterminate(true);
        bar.setStringPainted(true);
        bar.setString(message);
        dialog.add(bar);
        dialog.pack();
        return dialog;
    }

    private void getFromUniprotTerm() {
        spikeName = spikeNameTextField.getText();
        try {
            Map<String, String> uniprotContaminantSequencesByName = UniprotContentProvider.getUniprotSpikeSequencesByTerm(spikeName);
            if (uniprotContaminantSequencesByName != null && !uniprotContaminantSequencesByName.isEmpty()) {
                DialogConfirmContaminants dialogConfirmContaminants = new DialogConfirmContaminants(spikeSequenceMap, uniprotContaminantSequencesByName, parentFrame, true);
                dialogConfirmContaminants.setVisible(true);
                DefaultListModel model = (DefaultListModel) (jList.getModel());
                for (String aUniprotAccession : spikeSequenceMap.keySet()) {
                    model.addElement(aUniprotAccession);
                }
                jList.setModel(model);
                jList.repaint();
                jList.revalidate();
            } else {
                //custom title, warning icon
                JOptionPane.showMessageDialog(this,
                        "Could not find an uniprot entry for " + spikeName,
                        "Contaminant Not Found",
                        JOptionPane.WARNING_MESSAGE);
            }
        } catch (IOException ex) {
            Logger.getLogger(DialogUniprotContaminant.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.dispose();
    }

    private void getFromUniprotAccession() {
        spikeName = spikeNameTextField.getText();
        try {
            String sequence = UniprotContentProvider.getUniprotSpikeSequenceByAccession(spikeName);
            if (sequence != null && !sequence.isEmpty()) {
                spikeSequenceMap.put(spikeName, sequence);
                DefaultListModel model = (DefaultListModel) (jList.getModel());
                model.addElement(spikeName);
                jList.setModel(model);
                jList.repaint();
                jList.revalidate();
            } else {
                //custom title, warning icon
                JOptionPane.showMessageDialog(this,
                        "Could not find an uniprot entry for " + spikeName,
                        "Contaminant Not Found",
                        JOptionPane.WARNING_MESSAGE);
            }
        } catch (IOException ex) {
            Logger.getLogger(DialogUniprotContaminant.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.dispose();
    }

    public String getContaminantName() {
        return spikeName;
    }

    public void setContaminantName(String contaminantName) {
        this.spikeName = contaminantName;
    }

    private void spikeNameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_spikeNameTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_spikeNameTextFieldActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void searchOptionComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchOptionComboBoxActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_searchOptionComboBoxActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton searchButton;
    private javax.swing.JComboBox searchOptionComboBox;
    private javax.swing.JTextField spikeNameTextField;
    // End of variables declaration//GEN-END:variables
}
